package com.cl.unipay4j.wx;

import com.cl.unipay4j.core.IPayConfig;
import com.cl.unipay4j.core.pay.PayResponse;
import com.cl.unipay4j.core.util.MoneyUtil;
import com.cl.unipay4j.wx.sdk.WXPay;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @ClassName AbstractWxPay
 * @Description
 * @Author Small
 * @Date 2019/11/28 9:44
 * @Version 1.0
 **/
@Slf4j
public abstract class AbstractWxPay {

    protected WxPayConfigImpl wxPayConfig;

    public AbstractWxPay() {
        wxPayConfig = WxPayConfigImpl.getInstance();
        WxPayConfig config = new WxPayConfig();
        config.setAppAppId(WxConfiguration.getAppAppId());
        config.setAppid(WxConfiguration.getAppid());
        config.setAppletAppid(WxConfiguration.getAppletAppid());
        config.setKey(WxConfiguration.getKey());
        config.setMchid(WxConfiguration.getMchid());
        config.setSignType(WxConfiguration.getSignType());
        config.setNotifyurl(WxConfiguration.getNotifyUrl());
        config.setAutoReport(WxConfiguration.getAutoReport());
        config.setCertPath(WxConfiguration.getCertPath());
        wxPayConfig.setContext(config);
    }


    public AbstractWxPay(IPayConfig payConfig) {
        wxPayConfig = WxPayConfigImpl.getInstance();
        wxPayConfig.setContext((WxPayConfig) payConfig);
    }

    protected WXPay initWxPay() {
        WxPayConfig context = wxPayConfig.getContext();
        WXPay wxpay = null;
        try {
            wxpay = new WXPay(wxPayConfig, context.getNotifyurl(), context.isAutoReport(), context.isUseSandbox());
        } catch (Exception e) {
            log.warn("初始化WxPay异常", e);
        }
        return wxpay;
    }

    protected PayResponse<Map<String, String>> wrapperPayResponse(Map<String, String> r) {
        PayResponse<Map<String, String>> response = new PayResponse<Map<String, String>>();
        response.setOutTradeNo(r.get("out_trade_no"));
        response.setTradeNo(r.get("transaction_id"));
        response.setTotalAmount(MoneyUtil.cent2Yuan(Integer.parseInt(r.get("total_fee"))));
        response.setBody(r);
        return response;
    }

}
